/*
** Copyright (c) 2010  Kimmo 'Rainy' Pekkola
**
** This program is free software: you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation, either version 3 of the License, or
** (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with this program.  If not, see http://www.gnu.org/licenses.
*/

#include "precompiled.h"
#include "thememanager.h"

//-----------------------------------------------------------------------------
/**
** Returns the singleton instance.
*/
CThemeManager& CThemeManager::instance()
{
    static CThemeManager manager;
    return manager;
}

//-----------------------------------------------------------------------------
/**
** Constructor.
*/
CThemeManager::CThemeManager() : QObject(NULL)
{
    m_bHasRefrection = false;
    m_bHasBackground = false;

#ifdef WITH_PHONON
    Phonon::MediaObject* sound = Phonon::createPlayer(Phonon::MusicCategory, Phonon::MediaSource(QString()));
    delete sound;
#endif
}

//-----------------------------------------------------------------------------
/**
** Destructor.
*/
CThemeManager::~CThemeManager()
{
#ifdef WITH_PHONON
    QMap<QString, Phonon::MediaObject*>::iterator iter = m_AudioObjects.begin();
#else
    QMap<QString, QSound*>::iterator iter = m_AudioObjects.begin();
#endif
    for ( ; iter != m_AudioObjects.end(); iter++)
    {
        delete iter.value();
    }
}

//-----------------------------------------------------------------------------
/**
** Resets the theme to the default.
*/
void CThemeManager::resetTheme()
{
    m_CurrentTheme.clear();

    m_MapImages.clear();
    m_MapColors.clear();
    m_MapSounds.clear();
    m_MapOffsets.clear();

#ifdef WITH_PHONON
    QMap<QString, Phonon::MediaObject*>::iterator iter = m_AudioObjects.begin();
#else
    QMap<QString, QSound*>::iterator iter = m_AudioObjects.begin();
#endif
    for ( ; iter != m_AudioObjects.end(); iter++)
    {
        delete iter.value();
    }
    m_AudioObjects.clear();

    m_bHasRefrection = true;
    m_bHasBackground = false;

    m_MapImages[IMAGE_NUMBERS] = ":/numbers.png";
    m_MapImages[IMAGE_PAUSE] = ":/button-pause.png";
    m_MapImages[IMAGE_RESET] = ":/button-reset.png";
    m_MapImages[IMAGE_START] = ":/button-start.png";
    m_MapImages[IMAGE_RIGHT_BUTTON] = ":/button-right.png";
    m_MapImages[IMAGE_LEFT_BUTTON] = ":/button-left.png";

    m_MapColors[COLOR_BACKGROUND] = QColor(225, 235, 221);
    m_MapColors[COLOR_HELP] = QColor(125, 135, 121);

    m_MapOffsets[OFFSET_LEFT_BUTTON] = QPoint(-10, 10);
    m_MapOffsets[OFFSET_RIGHT_BUTTON] = QPoint(10, 10);

    m_ButtonSize = QSize();
}

//-----------------------------------------------------------------------------
/**
** Returns a list of found themes.
**
** \return The list of themes.
*/
QStringList CThemeManager::getThemes()
{
    QStringList listThemes;

    // Read the themes from the folder
    QDir dirThemes(":/themes");
    if (dirThemes.exists())
    {
        dirThemes.setFilter(QDir::Dirs | QDir::NoDotAndDotDot);
        QFileInfoList listDirs = dirThemes.entryInfoList();
        for (int i = 0; i < listDirs.size(); i++)
        {
            QFileInfo folderInfo = listDirs.at(i);
            listThemes.append(folderInfo.fileName());
        }
    }

    return listThemes;
}

//-----------------------------------------------------------------------------
/**
** Chooses the theme. If the theme is not found the default theme is selected.
**
** \param strTheme The name of the theme.
*/
void CThemeManager::chooseTheme(const QString& strTheme)
{
    QString strFolder = ":/themes/" + strTheme + "/";
    if (QFile::exists(strFolder + "theme.ini"))
    {
        QSettings theme(strFolder + "theme.ini", QSettings::IniFormat);
        if (theme.status() == QSettings::NoError)
        {
            m_MapImages.clear();
            m_MapColors.clear();
            m_MapSounds.clear();

            // general
            theme.beginGroup("general");
            m_bHasRefrection = theme.value("reflection", false).toBool();
            theme.endGroup();

            // images
            theme.beginGroup("images");
            m_bHasBackground = theme.contains("background");
            m_MapImages[IMAGE_BACKGROUND] = strFolder + theme.value("background").toString();
            m_MapImages[IMAGE_NUMBERS] = strFolder + theme.value("numbers").toString();
            m_MapImages[IMAGE_RESET] = strFolder + theme.value("reset").toString();
            m_MapImages[IMAGE_PAUSE] = strFolder + theme.value("pause").toString();
            m_MapImages[IMAGE_START] = strFolder + theme.value("start").toString();
            m_MapImages[IMAGE_LEFT_BUTTON] = strFolder + theme.value("leftbutton").toString();
            m_MapImages[IMAGE_RIGHT_BUTTON] = strFolder + theme.value("rightbutton").toString();
            theme.endGroup();

            // colors
            theme.beginGroup("colors");
            m_MapColors[COLOR_BACKGROUND] = QColor(theme.value("background").toString());
            m_MapColors[COLOR_HELP] = QColor(theme.value("help").toString());
            theme.endGroup();

            // sounds
            theme.beginGroup("sounds");
            QStringList ticks = theme.allKeys();
            foreach (QString tick, ticks)
            {
                QStringList listSound = tick.split("-");
                int value = listSound.last().toInt();
                if (listSound.first() == "down")
                {
                    value |= SOUND_DOWN;
                }
                else if (listSound.first() == "up")
                {
                    value |= SOUND_UP;
                }
                else if (listSound.first() == "time")
                {
                    value |= SOUND_TIME;
                }

                if (listSound.at(1) == "repeat")
                {
                    value |= SOUND_REPEAT;
                }

                m_MapSounds[value] = strFolder + theme.value(tick).toString();
            }
            theme.endGroup();

            // sizes
            theme.beginGroup("sizes");
            m_ButtonSize.setWidth(theme.value("buttonwidth").toInt());
            m_ButtonSize.setHeight(theme.value("buttonheight").toInt());
            theme.endGroup();

            // offsets
            theme.beginGroup("offsets");
            m_MapOffsets[OFFSET_LEFT_BUTTON] = QPoint(theme.value("leftbuttonx").toInt(), theme.value("leftbuttony").toInt());
            m_MapOffsets[OFFSET_RIGHT_BUTTON] = QPoint(theme.value("rightbuttonx").toInt(), theme.value("rightbuttony").toInt());
            theme.endGroup();

            m_CurrentTheme = strTheme;
            return;
        }
    }

    resetTheme();
}

//-----------------------------------------------------------------------------
/**
** Returns the given image for the theme.
**
** \param image The image to be returned.
** \return The image (if found).
*/
QImage CThemeManager::getImage(THEME_IMAGES image)
{
    if (image == IMAGE_BACKGROUND)
    {
        // Background needs to be 'fixed'
        QImage imgBG(m_MapImages[image]);
        QImage imgFixed(imgBG.size(), imgBG.format());

        int w = imgBG.size().width();
        int h = imgBG.size().height();
        QPainter painter(&imgFixed);
        painter.drawImage(0, 0, imgBG, w / 2, h / 2, w / 2, h / 2);
        painter.drawImage(w / 2, 0, imgBG, 0, h / 2, w / 2, h / 2);
        painter.drawImage(0, h / 2, imgBG, w / 2, 0, w / 2, h / 2);
        painter.drawImage(w / 2, h / 2, imgBG, 0, 0, w / 2, h / 2);
        return imgFixed;
   }
    return QImage(m_MapImages[image]);
}

//-----------------------------------------------------------------------------
/**
** Returns the given color for the theme.
**
** \param color The color to be returned.
** \return The color (if found).
*/
QColor CThemeManager::getColor(THEME_COLORS color)
{
    return m_MapColors[color];
}

//-----------------------------------------------------------------------------
/**
** Returns the given offset for the theme.
**
** \param offset The offset to be returned.
** \return The offset (if found).
*/
QPoint CThemeManager::getOffset(THEME_OFFSETS offset)
{
    return m_MapOffsets[offset];
}

//-----------------------------------------------------------------------------
/**
** Plays the sound (or runs the app) on the given second. If there is no sound
** defined for that second nothing is done.
**
** \param ticksWithFlags The current seconds with down/up/time flag.
** \return The sound object or NULL if nothing was played.
*/
QObject* CThemeManager::playSound(int ticksWithFlag)
{
    qDebug() << ticksWithFlag << m_MapSounds.keys();

    QString strAlarm;
    if (m_MapSounds.contains(ticksWithFlag))
    {
        // Check for absolute value
        strAlarm = m_MapSounds[ticksWithFlag];
    }
    else
    {
        // Check for repeat value
        QList<int> listKeys = m_MapSounds.keys();
        foreach (int key, listKeys)
        {
            if (key & SOUND_REPEAT)
            {
                if ((ticksWithFlag & SOUND_TICK_MASK) % (key & SOUND_TICK_MASK) == 0)
                {
                    strAlarm = m_MapSounds[key];
                    break;
                }
            }
        }

        // If no alarm was defined and we're down at 0 use the default alarm
        if (strAlarm.isEmpty() && (ticksWithFlag & SOUND_TICK_MASK) == 0 && (ticksWithFlag & SOUND_DOWN))
        {
            // Use the default alarm if counter is at the end and the theme doesn't define anything
            QSettings settings;
            strAlarm = settings.value("Alarm", ":/buzz.wav").toString();
        }
    }

    if (!strAlarm.isEmpty())
    {
        if (strAlarm.endsWith(".wav", Qt::CaseInsensitive) ||
            strAlarm.endsWith(".mp3", Qt::CaseInsensitive) ||
            strAlarm.endsWith(".aac", Qt::CaseInsensitive) ||
            strAlarm.endsWith(".flag", Qt::CaseInsensitive) ||
            strAlarm.endsWith(".mp4", Qt::CaseInsensitive) ||
            strAlarm.endsWith(".mp4a", Qt::CaseInsensitive) ||
            strAlarm.endsWith(".ogg", Qt::CaseInsensitive) ||
            strAlarm.endsWith(".wma", Qt::CaseInsensitive) ||
            strAlarm.endsWith(".au", Qt::CaseInsensitive))
        {
            // It's a known audio file so try to play it
#ifdef WITH_PHONON
            Phonon::MediaObject* sound = NULL;
            QMap<QString, Phonon::MediaObject*>::iterator iter = m_AudioObjects.find(strAlarm);
            if (iter == m_AudioObjects.end())
            {
                sound = Phonon::createPlayer(Phonon::MusicCategory, Phonon::MediaSource(strAlarm));
                m_AudioObjects[strAlarm] = sound;
            }
            else
            {
                sound = iter.value();
            }
            sound->pause();
            sound->seek(0);
            sound->play();
            if (!sound->isValid())
            {
                qDebug() << sound->errorString();
            }
#else
            QSound* sound = NULL;
            QMap<QString, QSound*>::iterator iter = m_AudioObjects.find(strAlarm);
            if (iter == m_AudioObjects.end())
            {
                sound = new QSound(strAlarm, this);
                m_AudioObjects[strAlarm] = sound;
            }
            else
            {
                sound = iter.value();
            }
            sound->play();
#endif
            return sound;
        }
        else
        {
            // It's not a known audio file so try to run it
            QProcess::startDetached(strAlarm);
        }
    }
    return NULL;
}

// EOF
